package com.cn.parks.servlet;

import com.alibaba.fastjson.JSON;
import com.cn.parks.dao.ParkingSeatDao;
import com.cn.parks.dao.UserCarDao;
import com.cn.parks.dao.UserDao;
import com.cn.parks.dao.impl.ParkingSeatDaoImpl;
import com.cn.parks.dao.impl.UserCarDaoImpl;
import com.cn.parks.dao.impl.UserDaoImpl;
import com.cn.parks.entity.ParkingSeat;
import com.cn.parks.entity.UserCar;
import com.cn.parks.entity.User;
import com.cn.parks.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@WebServlet("/parkingSeat/*")
public class ParkingSeatServlet extends HttpServlet {
    private ParkingSeatDao parkingSeatDao = new ParkingSeatDaoImpl();
    private UserCarDao userCarDao = new UserCarDaoImpl();
    private UserDao userDao = new UserDaoImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        String pathInfo = request.getPathInfo();
        try {
            if ("/getAll".equals(pathInfo)) {
                System.out.println("getAll");
                // 获取所有车位
                response.getWriter().write(JSON.toJSONString(Result.success(parkingSeatDao.getAll())));
            }else if ("/getById".equals(pathInfo)) {
                // 根据ID获取车位
                String seatId = request.getParameter("seatId");
                response.getWriter().write(JSON.toJSONString(Result.success(parkingSeatDao.getById(seatId))));
            } else if ("/getBySection".equals(pathInfo)) {
                // 根据区域搜索车位
                String section = request.getParameter("section");
                response.getWriter().write(JSON.toJSONString(Result.success(parkingSeatDao.getBySection(section))));
            } else if ("/getAvailableSeats".equals(pathInfo)) {
                // 所有获取空闲车位
                List<ParkingSeat> availableSeats = parkingSeatDao.getAvailableSeats();
                response.getWriter().write(JSON.toJSONString(Result.success(availableSeats)));
            }else if("/getTempAvailableSeats".equals(pathInfo)){
                //获取临时的空闲车位
                List<ParkingSeat> availableSpots = parkingSeatDao.getTempAvailableSeats();
                response.getWriter().write(JSON.toJSONString(Result.success(availableSpots)));
            }else if("/getFixedAndVip".equals(pathInfo)){
                //获取固定和vip的车位
                List<ParkingSeat> fixedAndVip = parkingSeatDao.getFixedAndVip();
                response.getWriter().write(JSON.toJSONString(Result.success(fixedAndVip)));
            }
        } catch (Exception e) {
            response.getWriter().write(JSON.toJSONString(Result.error(e.getMessage())));
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        String pathInfo = request.getPathInfo();
        try {
            if ("/insert".equals(pathInfo)) {
                // 添加车位
                ParkingSeat seat = JSON.parseObject(request.getReader().readLine(), ParkingSeat.class);
                if (parkingSeatDao.getBySeatNum(seat.getSeatNum()) != null){
                    response.getWriter().write(JSON.toJSONString(Result.error("此车位号已存在")));
                    return;
                }
                parkingSeatDao.insert(seat);
                response.getWriter().write(JSON.toJSONString(Result.success()));
            } else if ("/update".equals(pathInfo)) {
                // 更新车位
                ParkingSeat seat = JSON.parseObject(request.getReader().readLine(), ParkingSeat.class);
                parkingSeatDao.update(seat);
                response.getWriter().write(JSON.toJSONString(Result.success()));
            } else if ("/deleteById".equals(pathInfo)) {
                // 删除车位
                String seatId = JSON.parseObject(request.getReader().readLine()).getString("seatId");
                parkingSeatDao.deleteById(seatId);
                response.getWriter().write(JSON.toJSONString(Result.success()));
            } else if ("/updateState".equals(pathInfo)) {
                String requestBody = request.getReader().readLine();
                String seatId = JSON.parseObject(requestBody).getString("seatId");
                Integer state = JSON.parseObject(requestBody).getInteger("state");
                Integer carId = JSON.parseObject(requestBody).getInteger("carId");

                ParkingSeat seat = parkingSeatDao.getById(seatId);
                if (seat != null) {
                    // 如果是从空闲变为占用状态
                    if (seat.getSeatState() == 0 && state == 1) {
                        if (carId != null) {
                            // 获取车辆信息
                            UserCar car = userCarDao.getById(carId);
                            if (car != null) {
                                seat.setCarId(car.getCarId());
                                seat.setCarNumber(car.getCarNumber());
                                seat.setUserId(car.getUserId());
                                // 获取用户信息
                                User user = userDao.getById(car.getUserId());
                                if (user != null) {
                                    seat.setUserName(user.getUserName());
                                }
                            }
                        }
                    } 
                    // 如果是从占用变为空闲状态
                    else if (seat.getSeatState() == 1 && state == 0) {
                        seat.setCarId(null);
                        seat.setCarNumber(null);
                        seat.setUserId(null);
                        seat.setUserName(null);
                    }
                    
                    seat.setSeatState(state);
                    parkingSeatDao.update(seat);
                    response.getWriter().write(JSON.toJSONString(Result.success()));
                } else {
                    response.getWriter().write(JSON.toJSONString(Result.error("找不到车位")));
                }
            }
        } catch (Exception e) {
            response.getWriter().write(JSON.toJSONString(Result.error(e.getMessage())));
        }
    }
}